<template>
  <div>
    <el-form>
      <el-form-item>
        <el-input
          type="textarea"
          rows="14"
          v-model="log"
          placeholder="请输入mybatis sql log"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="restore">还原并复制</el-button>
        <el-button @click="clear">清空</el-button>
      </el-form-item>
      <el-form-item>
        <el-input type="textarea" rows="14" v-model="sql" readonly />
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  name: 'SqlLog',
  data() {
    return {
      log: '',
      sql: '',
    }
  },
  methods: {
    clear() {
      this.log = ''
      this.sql = ''
    },
    restore() {
      if (!this.log) {
        this.$message.warning('请输入mybatis sql log')
        return
      }

      let sqlAndParam = this.log.split('\n')
      if (sqlAndParam.length < 2) {
        this.$message.warning('格式错误')
        return
      }

      let sql = sqlAndParam[0].split('Preparing: ')
      if (sql.length != 2) {
        this.$message.warning('格式错误')
        return
      }
      let sqlStr = sql[1]

      let param = sqlAndParam[1].split('Parameters: ')
      if (param.length != 2) {
        this.$message.warning('格式错误')
        return
      }

      let params = param[1].split(',')
      for (let i = 0; i < params.length; i++) {
        let p = params[i]
        let paramAndType = p.split('(')

        if (
          paramAndType[1].indexOf('Integer') > -1 ||
          paramAndType[1].indexOf('Long') > -1
        ) {
          params[i] = paramAndType[0].trim()
        } else {
          params[i] = "'" + paramAndType[0].trim() + "'"
        }

        sqlStr = sqlStr.replace('?', params[i])
      }

      this.sql = sqlStr

      this.copy()
    },
    copy() {
      const input = document.createElement('input')
      input.value = this.sql
      document.body.appendChild(input)
      input.select() // 选择对象;
      document.execCommand('Copy') // 执行浏览器复制命令
      this.$message.success('还原并复制成功')
      input.remove()
    },
  },
}
</script>
